package com.jiazhong.mingxing.project.bookstore.front.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiazhong.mingxing.project.bookstore.commons.bean.Alipay;
import com.jiazhong.mingxing.project.bookstore.commons.bean.Book;
import com.jiazhong.mingxing.project.bookstore.commons.bean.Order;
import com.jiazhong.mingxing.project.bookstore.commons.bean.OrderItem;
import com.jiazhong.mingxing.project.bookstore.commons.config.JwtConfig;
import com.jiazhong.mingxing.project.bookstore.commons.mapper.OrderItemMapper;
import com.jiazhong.mingxing.project.bookstore.commons.mapper.OrderMapper;
import com.jiazhong.mingxing.project.bookstore.commons.util.JsonResult;
import com.jiazhong.mingxing.project.bookstore.commons.util.ResultTool;
import com.jiazhong.mingxing.project.bookstore.commons.util.SnowFlakeGenerateIdWorker;
import com.jiazhong.mingxing.project.bookstore.front.config.SpringMVCConfig;
import com.jiazhong.mingxing.project.bookstore.front.service.OrderService;
import com.jiazhong.mingxing.project.bookstore.front.service.ShoppingCartService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.List;

@Slf4j
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    @Resource
    private ShoppingCartService shoppingCartService;
    @Resource
    private OrderItemMapper orderItemMapper;
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private SnowFlakeGenerateIdWorker snowFlakeGenerateIdWorker;
    @Resource
    private RocketMQTemplate rocketMQTemplate;


    @Value("${appId}")
    private String appId;
    @Value("${privateKey}")
    private String privateKey;
    @Value("${publicKey}")
    private String publicKey;
    @Value("${notifyUrl}")
    private String notifyUrl;
    @Value("${returnUrl}")
    private String returnUrl;
    @Value("${signType}")
    private String signType;
    @Value("${charset}")
    private String charset;
    @Value("${gatewayUrl}")
    private String gatewayUrl;


    @SneakyThrows
    @Transactional(rollbackFor = Exception.class)
    public String saveOrder(String token) {
        // 0. 获取到录入的数据（购物车中数据）
        JsonResult<List<Book>> cart = shoppingCartService.findCartByUserId(token);
        List<Book> bookList = cart.getData();
        // 1. 获取到userId
        Object userId = JwtConfig.parseJWT(token).get("id");
        // 2. 向order表中录入一行数据（生成订单）
        Order order = new Order();
        order.setUserId(userId.toString());
        int count = 0;
        double price = 0;
        for (Book book : bookList) {
            count += book.getNumber();
            price += book.getPrice() * book.getNumber();
        }
        order.setStatus(0);
        NumberFormat format = new DecimalFormat("0.00");
        String formatNumber = format.format(price);
        order.setTotalAmount(Double.parseDouble(formatNumber));
        order.setTotalCount(count);
        long orderId = snowFlakeGenerateIdWorker.nextId();
        order.setId(orderId + "");
        orderMapper.insert(order);
        // 3. 向order_item表中录入多行数据（生成订单详情）
        for (Book book : bookList) {
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(orderId + "");
            orderItem.setBookId(book.getId());
            orderItem.setNumber(book.getNumber());
            orderItemMapper.insert(orderItem);
        }
        // 4. 向rocketMQ中写入一个半事务消息
        MessageBuilder<String> messageBuilder = MessageBuilder
                .withPayload(JSONArray.toJSONString(bookList))
                .setHeader("KEYS", orderId + "," + price);
        rocketMQTemplate.sendMessageInTransaction("order:stock", messageBuilder.build(), JSONArray.toJSONString(bookList));
        // 5. 开始支付宝支付
        Alipay alipay = new Alipay();
        alipay.setOut_trade_no(orderId + "");
        alipay.setTotal_amount(formatNumber);
        alipay.setSubject(userId + "的订单，订单号:" + orderId);
        alipay.setBody(userId + "购买了" + price);
        log.info("alipay:{}", alipay);
        SpringMVCConfig.alipayClient = new DefaultAlipayClient(gatewayUrl, appId, privateKey,
                "json", charset, publicKey, signType);
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(returnUrl);
        alipayRequest.setNotifyUrl(notifyUrl);
        String jsonString = JSONArray.toJSONString(alipay);
        alipayRequest.setBizContent(jsonString);
        return SpringMVCConfig.alipayClient.pageExecute(alipayRequest).getBody();
    }
}
